<?php
/*
 * kernel/object.tools.php
 *
 * This code is distributed and used under the GNU GPL v2 License,
 * please, read file LICENSE, which is situated in root directory,
 * or in "LICENSE" directory with most acceptable translation for you
 *
 * Copyright (C) 2010, Taras Kudla
 *
 */
 
class gTools extends gKernel {
	# creates action ( registration of new module function )
	public function createaction($module,$method,$guest=false,$runmode=0,$position=1,$runwith=0,$withmod="",$onstart=false,$weight=0,$comment="",$levels=null){
		//if($this->core->getenvlayer()!=_ENV_MOD){
		//	return $this->core->error("TOOLS","Cannot create action in module run environment");
		//}
		if( !$this->core->cms->checkmodpermission(_PERM_WRITESQL)){
			$this->core->error("tools","Permission denied, module '".$this->core->getenvcaller("mod")."' cann't change system options");
			return false;
		}
		# preparing
		$hash = $this->core->cms->GetHash($module,$method);
		$alias = $this->core->cms->GetAlias($module,$method);
		$this->deleteaction($hash);
		if( !$this->core->dbo->select("actions","controller","where hash='$hash' limit 1 offset 0",_RESULT_BOOL)){
			# preparing for registartion
			$insert = $this->core->dbo->insert("actions",array(
				"hash"=>$hash,
				"alias"=>$alias,
				"moduler"=>$module,
				"action"=>$method,
				"guest"=>(int)$guest,
				"runmode"=>$runmode,
				"position"=>$position,
				"runwith"=>$runwith,
				"onstart"=>(int)$onstart,
				"weight"=>$weight,
				"withmod"=>$withmod,
				"comment"=>$comment,
				"extime"=>0,
				"memuse"=>0,
				"lastsum"=>0
				));
		}
		# preparing for levellinks
		if( !is_array($levels)){
			$levels=array(_FUNC_USER);
		}
		# clering all levellinks as trash
		$this->core->dbo->delete("levellinks","where hash='$hash'");
		# inserting levellinks
		foreach( $levels as $k=>$v){
			if( !$this->core->dbo->select("levellinks","hash","where hash='$hash' and level='$v' limit 1 offset 0",_RESULT_BOOL)){
				$this->core->dbo->insert("levellinks",array("hash"=>$hash,"level"=>$v));
			}
		}
	}
	# 
	
	# action removing
	public function deleteaction($module,$method=null){
		if( $method!=null)
		$hash = $this->core->cms->GetHash($module,$method);
		else $hash = $module;
		$this->core->dbo->delete("actions","where hash='$hash'");
		$this->core->dbo->delete("levellinks","where hash='$hash'");	
	}
	public function createlangterm(){
		
	}
	public function deletelangterm(){
		
	}
	# converts russian utf8 text in latin characters text
	public function rustotranslit($input){
		$output = str_replace(array(
		"А","Б","В","Г","Д","Е","Э","Ж","З","И","Ы","Й","К","Л","М","Н","П","Р","О","С","Т","Ф","Х","Ч","Ш","Щ",
		"Ц","Ю","Ъ","Я","Ё","У",
		"а","б","в","г","д","е","Э","ж","з","и","ы","й","к","л","м","н","п","р","о","с","т","ф","х","ч","ш","щ",
		"ц","ю","ъ","я","ё","у"
		),array(
		"A","B","V","G","D","YE","E","j","Z","I","U","Y","K","L","M","N","P","R","O","S","T","F","H","CH","SH","SHCH",
		"TS","YU","","YA","YO","U",
		"a","b","v","g","d","ye","e","j","z","i","u","y","k","l","m","n","p","r","o","s","t","f","h","ch","sh","shch",
		"ts","yu","","ya","yo","u"
		),$input);
		return $output;
	}
	# converts ukrainian utf8 text in latin characters text
	public function ukrtotranslit($input){
		$output = str_replace(array(
		"А","Б","В","Г","Ґ","Д","Е","Є","Ж","З","И","І","Ї","Й","К","Л","М","Н","П","Р","О","С","Т","Ф","Х","Ч","Ш","Щ",
		"Ц","Ю","Ь","Я","У",
		"а","б","в","г","ґ","д","е","є","ж","з","и","і","ї","й","к","л","м","н","п","р","о","с","т","ф","х","ч","ш","щ",
		"ц","ю","ь","я","у"
		),array(
		"A","B","V","G","G","D","E","E","j","Z","U","I","I","Y","K","L","M","N","P","R","O","S","T","F","H","CH","SH","SHCH",
		"TS","YU","","YA","U",
		"a","b","v","g","g","d","e","e","j","z","u","i","i","y","k","l","m","n","p","r","o","s","t","f","h","ch","sh","shch",
		"ts","yu","","ya","u"
		),$input);
		return $output;
	}
	# preparing for alias name
	public function preparealiasname($string){
		$result = preg_replace("/[^A-zА-я0-9_]/u","_",$string);
		$result = preg_replace("/\\\/","_",$result);
		$result = preg_replace("/^_*([A-z0-9])/","$1",$result);
		$result = preg_replace("/([A-z0-9])_*$/","$1",$result);
		$result = preg_replace("/_+/","_",$result);
		if( strlen($result)>200)
			$result = substr($result,0,200);
		return strtolower($result);
	}	

	/*
	 * FIXME: 
	 */
	# array to xml
	# from: http://snipplr.com
	public function arraytoxml($data, $rootNodeName = 'data', $xml=null){
	    #
	    if (ini_get('zend.ze1_compatibility_mode') == 1){
		ini_set ('zend.ze1_compatibility_mode', 0);
	    }
	    if ($xml == null){
		$xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
	    }
	    foreach($data as $key => $value){
		if (is_numeric($key)){
		    $key = "unknownNode_". (string) $key;
		}
		$key = preg_replace('/[^a-z]/i', '', $key);
		if (is_array($value)){
		    $node = $xml->addChild($key);
		    $this->arraytoxml($value, $rootNodeName, $node);
		}
		else {
		    //$value = htmlentities($value);
		    $xml->addChild($key,"<![CDATA[ ".$value." ]]>");
		}
	    }
	    return $xml->asXML();
	}



	# builds form from array
	# TODO: It's really ugly, but it was written in 15 minutes )
	public function FormGenerator(&$__,$style=0)
		{

		$i=0;

		$_="<form ";

		$id=rand(100,999);

		$__["options"]["id"]=$id;

		$__["options"]["name"]=$id;
		
		$env = $this->core->getenvcaller();
		
		if(isset($__["options"]["action"]) && $this->core->get("runmode")==_HTML_RUNMODE)
			{

            if(is_numeric($__["options"]["action"])){
            $__["options"]["action"]=$this->core->base->GetActionLink($__["options"]["action"]); }
            else
            $__["options"]["action"]="";
			}
			
		if(isset($__["options"]["action"]) && $this->core->get("runmode")==_AJAX_RUNMODE){
			
			if(!is_numeric($__["options"]["action"])){
				
				$__["options"]["action"]=$env["ID"];
			}
			
		}

		foreach($__["options"] as $k=>$v)
			{

			$_.="".$k."='".$v."' ";

			}
        if($style==0)
		$_.="><table id='formtable'>".( (isset($__["title"])) ? "<tr><td colspan='2'><div class='formtitle'>".$__["title"]."</div><td></tr>":"" );
		else
        $_.="><table id='formtable'>".( (isset($__["title"])) ? "<tr><td ><div class='formtitle'>".$__["title"]."</div><td>":"" );
       
		while ($i<count($__["input"]))
			{
			$f=null;

			$t=null;

			$s=null;

            if($style==0)
			$_.="<tr><td valign='top'>".( (isset($__["input"][$i]["title"]))? "<div  class='forminputtitle'>".$__["input"][$i]["title"]."</div>":"" )."</td><td>";
			else
            $_.="<td valign='top'>".( (isset($__["input"][$i]["title"]))? "<div  class='forminputtitle'>".$__["input"][$i]["title"]."</div>":"" )."</td><td>";

			if(isset($__["input"][$i]["String"])) { $f=1; $_.=$__["input"][$i]["String"]; }

			if(isset($__["input"][$i]["type"]) && $__["input"][$i]["type"]=="textarea") { $f=2; $_.="<textarea "; unset($__["input"][$i]["type"]);  }

			if(isset($__["input"][$i]["type"]) 
			&& ($__["input"][$i]["type"]=="text" 
			|| $__["input"][$i]["type"]=="password"   ) 
			&& $this->core->get("runmode")==_AJAX_RUNMODE ){
				
				//$__["input"][$i]["onKeyPress"]="javascript:keyForm(\"".$id."\",event);";
			}
			
			
			
			if(isset($__["input"][$i]["type"]) && ( $__["input"][$i]["type"]=="Submit" || ($__["input"][$i]["type"]=="Button" && $__["input"][$i]["name"]=="Submit" )) ) //&& ( isset($__["input"][$i]["onClick"]) ||  $__["input"][$i]["name"]=="Submit"  ))
				{
				if($this->core->get("runmode")==_HTML_RUNMODE)
					{
					$__["input"][$i]["type"]="Submit";

					$__["input"][$i]["name"]="Submit";

					$__["input"][$i]["onClick"]="javascript:void(0);";

					$__["input"][$i]["class"]="button";

					}

				if($this->core->get("runmode")==_AJAX_RUNMODE)
					{
					$__["input"][$i]["type"]="Button";

					$__["input"][$i]["name"]="Submit";

					//if(isset($__["input"][$i]["where"])) { }

					$__["input"][$i]["onClick"]="javascript:processForm(this.form);";//\"".$id."\");";

					$__["input"][$i]["class"]="button";


					}


				}

			$_.=($f==null)?"<input ":"";

			foreach($__["input"][$i] as $k=>$v)
				{
				if($f==null || $f==2)
					{
				if($f==2 && $k=="value")continue;
				$_.="".$k."='".$v."' ";
					}
				else break;

				}

			$_.=($f==null)?" />":"";

			if($f==2) { $_.=">".( (isset($__["input"][$i]["value"]))? $__["input"][$i]["value"]:"" )."</textarea>"; }

            if($style==0)
			$_.="</td></tr>";
			else
            $_.="</td>";


			$i++;

			}

		//$_.=$__["other"];
		if($style==1)$_.="</tr>";

		return $_."</table></form>";

		}
			
	public function TableGenerator(&$_)
		{
			$t="<table id='GeneratedTable' cellpadding='0' cellspacing='0'>";

			$cols=null;

			if(isset($_["names"]))
				{
				$t.="<tr>";

				foreach($_["names"] as $k=>$v)
					{
						$t.="<td class='GeneratedTableHeader'>".$v."</td>";
					}

				$t.="</tr>";
				}

			if(!isset($_["values"]) || count($_["values"])==0)return $t."</table>";

			if(isset($_["qnames"]))
			$keys=$_["qnames"];
			else
			{
				$keys=null;

				foreach($_["values"][0] as $k=>$v)
				$keys[]=$k;
			}

			$i=0;

			while($i<count($_["values"]))
				{
					$t.="<tr>";

					foreach($keys as $k=>$v){
					if(isset($_["links"]) && isset($_["links"][$v]) && isset($_["links"][$v]["func"])  && isset($_["links"][$v]["name"]))
						{
						$p=null;

						if(isset($_["links"][$v]["paramname"]))
							{
								$p=$_["links"][$v]["paramname"];
							
								if(isset($_["links"][$v]["paramvalue"]))
								$p.="=".$_["values"][$i][$_["links"][$v]["paramvalue"]];
							
							}

						$o=$this->BuildActionLink($_["links"][$v]["func"],$p,$_["values"][$i][$_["links"][$v]["name"]],(isset($_["links"][$v]["style"])?$_["links"][$v]["style"]:null));

						}
					else
					$o=$_["values"][$i][$v];


					$t.="<td>".$o."</td>";

					}
					$t.="</tr>";

					$i++;
				}

			return $t."</table>";			
		}
	
	/*
	 * Simple Pages Links Generator
	 */
	public function pages($action,$total,$current,$separator="page",$currentparams=null,$module=null){
		if( ($current==0 && $total==0) || $total==1)
			return null;
		if( $currentparams==null){
					$call = $this->core->base->getcall();
					$currentparams = null;
					if( is_array($call["paramsarray"])){
						unset($call["paramsarray"][$separator]);
						$i=0;
						foreach( $call["paramsarray"] as $k=>$v){
							$currentparams .=($i>0?"&":null).$k.(!empty($v)?"=$v":null);
							$i++;
						}
					} else $currentparams = preg_replace("/\&$separator\=[A-z0-9_]+/i",null,$call["params"]);
		}
		$params=($currentparams!=null)?$currentparams."&".$separator."=":"".$separator."=";
		$a=null;
		$a.="<a href=\"".$this->core->base->GetActionLink($action,$params."0")."\">1</a> ";
		for($i=1;$i<$total-1;$i++){
				if($i==($current-1))$a.=" ...<a href=\"".$this->core->base->GetActionLink($action,$params.$i)."\">".($i+1)."</a> ";
				if($i==($current))$a.="<a href=\"".$this->core->base->GetActionLink($action,$params.$i)."\">".($i+1)."</a> ";
				if($i==($current+1))$a.=" <a href=\"".$this->core->base->GetActionLink($action,$params.$i)."\">".($i+1)."</a> "."... ";
		}
		$a.=" <a href=\"".$this->core->base->GetActionLink($action,$params.($total-1))."\">".($total)."</a>";
		return $a;
		}
}